<template>
	<view class="home" :style="bgStyle">
		<custom-navbar :title="t('home.title')" :transparent="true" />

		<view class="content p0030 pb150" :style="{ paddingTop: navBarHeight + 'px' }">
			<!-- 状态判断：未登录 -->
			<user-login-panel style="width: 100%;" v-if="pageStatus === 'not_logged'" @login="handleWechatLogin" />

			<!-- 状态判断：需注册 -->
			<user-register-panel style="width: 100%;" v-else-if="pageStatus === 'need_register'"
				:register-info="registerInfo" :is-getting-user-info="isGettingUserInfo" :is-registering="isRegistering"
				@get-user-info="onGetUserInfo" @get-phone-number="getPhoneNumber" @register="handleRegister" />

			<!-- 状态判断：已登录 -->
			<user-profile-panel style="width: 100%;" v-else-if="pageStatus === 'logged_in'" :user-info="userInfo"
				:menu-items="listdata" @logout="handleLogout" @edit-profile="editProfile" @navigate="handlePath"
				@policy="handlePolicy" @supply="handleSupply" @talent="handleTalent" @intention="handleIntention" />

			<!-- 底部协议信息 -->
			<view class="footer-agreement f265c9 mt60 fc">
				<view class="mr5" @click="handleagreement(1)">用户协议</view> I <view class="ml5"
					@click="handleagreement(2)">隐私政策
				</view>
			</view>
		</view>

		<custom-tabbar />
	</view>
</template>

<script setup>
	import {
		ref,
		computed,
		onMounted,
		onUnmounted
	} from 'vue'
	import {
		useI18n
	} from 'vue-i18n'
	import {
		onShow
	} from '@dcloudio/uni-app'
	import {
		loginByWechatCode,
		registerUser
	} from '@/api/login'
	import {
		getUsInfo
	} from '@/api/user'
	import CustomTabbar from '@/components/custom-tabbar.vue'
	import CustomNavbar from '@/components/custom-navbar.vue'
	import UserLoginPanel from '@/components/user/UserLoginPanel.vue'
	import UserRegisterPanel from '@/components/user/UserRegisterPanel.vue'
	import UserProfilePanel from '@/components/user/UserProfilePanel.vue'

	const {
		t
	} = useI18n()

	// 页面状态管理
	const pageStatus = ref('checking') // checking | not_logged | logging | need_register | logged_in

	// 注册相关状态
	const isRegistering = ref(false)
	const isGettingUserInfo = ref(false)
	const registerInfo = ref({
		openid: '',
		nickname: '',
		avatar: '',
		code: '',
		lang_code: 'zh'
	})

	// 用户数据
	const userInfo = ref(uni.getStorageSync('userInfo') || {})

	// 系统信息
	const systemInfo = uni.getSystemInfoSync()
	const navBarHeight = computed(() => systemInfo.statusBarHeight + 44)
	const bgStyle = ref({})

	// 菜单数据
	const listdata = ref([{
			icon: '/static/images/user/活动.svg',
			name: '我的活动',
			go: '/static/images/user/go.svg',
			line: true,
			path: "/pages/user/activity"
		},
		{
			icon: '/static/images/user/预约.svg',
			name: '我的预约',
			go: '/static/images/user/go.svg',
			line: true,
			path: "/pages/user/subscribe"
		},
		{
			icon: '/static/images/user/反馈.svg',
			name: '我的反馈',
			go: '/static/images/user/go.svg',
			line: true,
			path: "/pages/user/feedback"
		},
		{
			icon: '/static/images/user/金融.svg',
			name: '我的金融',
			go: '/static/images/user/go.svg',
			line: true,
			path: "/pages/user/financial"
		},
		{
			icon: '/static/images/user/人才库.svg',
			name: '人才库',
			go: '/static/images/user/go.svg',
			line: true,
			path: "/pages/resume/index"
		},
		{
			icon: '/static/images/user/留言.svg',
			name: '留言箱',
			go: '/static/images/user/go.svg',
			line: false,
			path: "/pages/user/leave"
		}
	])

	// 检查token是否有效
	const checkTokenValid = () => {
		const token = uni.getStorageSync('token')
		if (!token?.access_token) return false
		return token.expires_at > Date.now() + 300000
	}

	// 统一登录处理函数
	const handleLoginResponse = (res) => {
		if (res.code === 200) {
			return {
				code: 200,
				data: res.data
			}
		} else if (res.code === 402 || res.message === '请注册') {
			const openid = res.data?.openid || res.openid || ''
			if (!openid) {
				throw new Error('未获取到 openid')
			}
			return {
				code: 402,
				data: {
					openid
				}
			}
		} else {
			throw new Error(res.message || `登录失败，错误码: ${res.code}`)
		}
	}

	// 静默登录方法
	const trySilentLogin = async () => {
		try {
			// 1. 检查现有token是否有效
			if (checkTokenValid()) {
				return {
					code: 200
				}
			}

			// 2. 执行微信静默登录
			const {
				code: wxCode
			} = await new Promise((resolve, reject) => {
				uni.login({
					provider: 'weixin',
					success: resolve,
					fail: (err) => reject(new Error(`微信登录失败: ${err.errMsg}`))
				})
			})

			// 3. 调用登录接口并统一处理响应
			const res = await loginByWechatCode({
				js_code: wxCode,
				lang_code: 'zh'
			})

			return handleLoginResponse(res)
		} catch (error) {
			console.error('静默登录失败:', error)
			return {
				code: error.message.includes('请注册') ? 402 : 401,
				message: error.message
			}
		}
	}

	// 获取用户信息
	const fetchUserInfo = async () => {
		try {
			const res = await getUsInfo()
			if (res.code === 200) {
				userInfo.value = res.data
				uni.setStorageSync('userInfo', res.data)
				return true
			}
			return false
		} catch (error) {
			console.error('获取用户信息失败:', error)
			return false
		}
	}

	// 登录成功处理
	const handleLoginSuccess = async (data) => {
		// 存储token
		const tokenData = {
			access_token: data.token.access_token,
			refresh_token: data.token.refresh_token,
			expires_at: Date.now() + data.token.expires_in * 1000,
			token_type: data.token.token_type
		}
		uni.setStorageSync('token', tokenData)

		// 获取用户信息
		const success = await fetchUserInfo()

		if (success) {
			pageStatus.value = 'logged_in'
			uni.showToast({
				title: data.message || '登录成功',
				icon: 'success'
			})
		} else {
			// 获取用户信息失败，视为未登录状态
			pageStatus.value = 'not_logged'
			uni.showToast({
				title: '获取用户信息失败',
				icon: 'none'
			})
		}
	}

	// 检查登录状态
	const checkLoginStatus = async () => {
		try {
			pageStatus.value = 'checking';

			// 1. 先检查本地token是否有效
			if (checkTokenValid()) {
				// 2. 尝试获取用户信息
				const success = await fetchUserInfo();
				if (success) {
					pageStatus.value = 'logged_in';
					return true;
				}
			}

			// 3. 执行静默登录
			const res = await trySilentLogin();

			if (res.code === 200) {
				await handleLoginSuccess(res.data);
				return true;
			} else if (res.code === 402) {
				// 需要注册的情况
				pageStatus.value = 'need_register';
				registerInfo.value.openid = res.data?.openid || '';
				return false;
			} else {
				pageStatus.value = 'not_logged';
				return false;
			}
		} catch (error) {
			console.error('检查登录状态失败:', error);
			pageStatus.value = 'not_logged';
			return false;
		}
	};

	// 微信登录
	const handleWechatLogin = async () => {
		if (pageStatus.value === 'logging') return

		try {
			pageStatus.value = 'logging'
			uni.showLoading({
				title: '登录中...',
				mask: true
			})

			// 1. 获取微信code
			const {
				code: wxCode
			} = await new Promise((resolve, reject) => {
				uni.login({
					provider: 'weixin',
					success: resolve,
					fail: (err) => reject(new Error(err.errMsg))
				})
			})

			// 2. 调用登录接口
			const res = await loginByWechatCode({
				js_code: wxCode,
				lang_code: 'zh'
			})

			// 3. 统一处理登录结果
			const loginRes = handleLoginResponse(res)

			if (loginRes.code === 402) {
				pageStatus.value = 'need_register'
				registerInfo.value.openid = loginRes.data?.openid || ''
				uni.setStorageSync('registerInfo', registerInfo.value)
			} else if (loginRes.code === 200) {
				await handleLoginSuccess(loginRes.data)
			}
		} catch (error) {
			console.error('微信登录失败:', error)
			uni.showToast({
				title: error.message || '登录失败',
				icon: 'none'
			})
			pageStatus.value = 'not_logged'
		} finally {
			uni.hideLoading()
		}
	}

	// 获取头像昵称
	const onGetUserInfo = async (e) => {
		if (e.detail.errMsg !== 'getUserInfo:ok') {
			uni.showToast({
				title: '请允许获取头像和昵称',
				icon: 'none'
			})
			return
		}

		isGettingUserInfo.value = true
		try {
			registerInfo.value.nickname = e.detail.userInfo.nickName
			registerInfo.value.avatar = e.detail.userInfo.avatarUrl
			uni.setStorageSync('registerInfo', registerInfo.value)
			uni.showToast({
				title: '获取信息成功',
				icon: 'success'
			})
		} finally {
			isGettingUserInfo.value = false
		}
	}

	// 获取手机号
	const getPhoneNumber = async (e) => {
		if (e.detail.errMsg !== 'getPhoneNumber:ok') {
			uni.showToast({
				title: '请允许获取手机号',
				icon: 'none'
			})
			return
		}

		try {
			registerInfo.value.code = e.detail.code
			uni.setStorageSync('registerInfo', registerInfo.value)
			uni.showToast({
				title: '手机号授权成功',
				icon: 'success'
			})
		} catch (error) {
			console.error('获取手机号失败:', error)
			uni.showToast({
				title: '授权失败',
				icon: 'none'
			})
		}
	}

	// 注册用户
	const handleRegister = async () => {
		// 验证所有必填字段
		const requiredFields = {
			openid: '未获取到用户标识，请重新登录',
			nickname: '请先获取头像和昵称',
			avatar: '请先获取头像和昵称',
			code: '请先获取手机号授权'
		}

		for (const [field, message] of Object.entries(requiredFields)) {
			if (!registerInfo.value[field]) {
				uni.showToast({
					title: message,
					icon: 'none',
					duration: field === 'openid' ? 3000 : 2000
				})
				return
			}
		}

		isRegistering.value = true
		try {
			uni.showLoading({
				title: '注册中...',
				mask: true
			})

			const res = await registerUser({
				openid: registerInfo.value.openid,
				nickname: registerInfo.value.nickname,
				avatar: registerInfo.value.avatar,
				lang_code: 'zh',
				code: registerInfo.value.code
			})

			if (res.code === 200) {
				await handleLoginSuccess(res.data)
				uni.removeStorageSync('registerInfo')
			} else {
				throw new Error(res.message || '注册失败')
			}
		} catch (error) {
			console.error('注册失败:', error)
			uni.showToast({
				title: error.message || '注册失败',
				icon: 'none'
			})
		} finally {
			isRegistering.value = false
			uni.hideLoading()
		}
	}

	// 退出登录
	const handleLogout = () => {
		uni.showModal({
			title: '提示',
			content: '确定要退出登录吗？',
			success: (res) => {
				if (res.confirm) {
					uni.removeStorageSync('token')
					uni.removeStorageSync('userInfo')
					userInfo.value = {}
					pageStatus.value = 'not_logged'
				}
			}
		})
	}

	// 页面跳转
	const handlePath = (path) => {
		if (!path) {
			uni.showToast({
				title: '功能正在开发中',
				icon: 'none'
			})
			return
		}

		const needLoginPaths = [
			'/pages/user/activity', '/pages/user/subscribe',
			'/pages/user/feedback', '/pages/user/financial',
			'/pages/user/talent', '/pages/user/leave'
		]

		if (needLoginPaths.includes(path) && pageStatus.value !== 'logged_in') {
			uni.showModal({
				title: '提示',
				content: '此功能需要登录后才能使用，是否立即登录？',
				success: (res) => {
					if (res.confirm) handleWechatLogin()
				}
			})
			return
		}

		uni.navigateTo({
			url: path
		})
	}

	// 编辑资料
	const editProfile = () => {
		uni.navigateTo({
			url: '/pages/user/profile'
		})
	}

	// 收藏相关跳转
	const handlePolicy = () => {
		if (pageStatus.value !== 'logged_in') {
			uni.showModal({
				title: '提示',
				content: '此功能需要登录后才能使用，是否立即登录？',
				success: (res) => {
					if (res.confirm) handleWechatLogin()
				}
			})
			return
		}

		uni.navigateTo({
			url: '/pages/user/policy'
		})
	}

	const handleSupply = () => {
		if (pageStatus.value !== 'logged_in') {
			uni.showModal({
				title: '提示',
				content: '此功能需要登录后才能使用，是否立即登录？',
				success: (res) => {
					if (res.confirm) handleWechatLogin()
				}
			})
			return
		}

		uni.navigateTo({
			url: '/pages/user/supply'
		})
	}

	const handleTalent = () => {
		if (pageStatus.value !== 'logged_in') {
			uni.showModal({
				title: '提示',
				content: '此功能需要登录后才能使用，是否立即登录？',
				success: (res) => {
					if (res.confirm) handleWechatLogin()
				}
			})
			return
		}

		uni.navigateTo({
			url: '/pages/user/talent'
		})
	}

	const handleIntention = () => {


		uni.navigateTo({
			url: '/pages/user/intention'
		})
	}

	const handleagreement = (val) => {

		uni.navigateTo({
			url: `/pages/user/agreement?type=${val}`
		})
	}

	// 初始化
	onMounted(() => {
		bgStyle.value = {
			backgroundImage: `url(https://gx.jifgou.com/image/homebg.png)`,
			backgroundSize: '100% auto',
			backgroundRepeat: 'no-repeat',
			minHeight: '100vh'
		}

		// 初始化检查登录状态
		checkLoginStatus()
		// 监听登录检查事件
		uni.$on('checkLoginStatus', checkLoginStatus);
	})
	onUnmounted(() => {
		uni.$off('checkLoginStatus');
	});
	// 页面显示时检查
	onShow(() => {
		console.log(111)
		// 如果当前是已登录状态，刷新用户信息
		if (pageStatus.value === 'logged_in') {
			fetchUserInfo()
		}

		// 如果是从其他页面返回，检查token是否过期
		if (pageStatus.value === 'logged_in' && !checkTokenValid()) {
			// token过期，重新检查登录状态
			checkLoginStatus()
		}
	})
</script>

<style lang="scss" scoped>
	/* 原有样式保持不变 */
	.home {
		width: 100%;
		min-height: 100vh;
		position: relative;

		.content {
			padding-top: var(--status-bar-height);
			padding-top: calc(var(--status-bar-height) + 44px);
			display: flex;
			flex-direction: column;
			align-items: center;

			.unlogin-container {
				width: 100%;
				height: 60vh;

				.unlogin-tip {
					font-size: 28rpx;
					color: #999;
				}

				.login-btn {
					width: 200rpx;
					height: 80rpx;
					line-height: 80rpx;
					background: linear-gradient(90deg, #4A90E2, #5D9BF2);
					color: white;
					border-radius: 40rpx;
					font-size: 28rpx;
				}
			}

			.register-container {
				width: 100%;
				padding: 0 40rpx;
				box-sizing: border-box;

				.register-title {
					font-weight: bold;
				}

				.avatar-container {
					width: 180rpx;
					height: 180rpx;
					position: relative;

					.avatar {
						width: 100%;
						height: 100%;
						border-radius: 50%;
						border: 2rpx solid #eee;
					}

					.change-avatar {
						position: absolute;
						bottom: 0;
						width: 100%;
						height: 40rpx;
						line-height: 40rpx;
						background: rgba(0, 0, 0, 0.5);
						color: white;
						border-radius: 0 0 80rpx 80rpx;
						font-size: 20rpx;
					}
				}

				.info-item {
					width: 100%;
					height: 60rpx;
					border-bottom: 1rpx solid #f5f5f5;
				}

				.get-phone-btn {
					width: 100%;
					height: 80rpx;
					line-height: 80rpx;
					border: 2rpx solid #4A90E2;
					color: #4A90E2;
					border-radius: 40rpx;
					background: transparent;
				}

				.register-btn {
					width: 100%;
					height: 80rpx;
					line-height: 80rpx;
					background: linear-gradient(90deg, #4A90E2, #5D9BF2);
					color: white;
					border-radius: 40rpx;
					opacity: 0.9;

					&:disabled {
						opacity: 0.5;
						background: #ccc;
					}
				}
			}

			.user {
				width: 100%;

				.img {
					width: 100rpx;
					height: 100rpx;
					border-radius: 50%;
				}

				.login {
					.img {
						width: 24rpx;
						height: 24rpx;
						margin-left: 10rpx;
					}
				}

				.btn {
					width: 100rpx;
					height: 50rpx;
					background: rgba(255, 255, 255, 0.5);
					border-radius: 500rpx;
					border: 2rpx solid #ffffff;
				}
			}

			.collect {
				width: 100%;
				height: 180rpx;
				background: #FFFFFF;
				border-radius: 20rpx;
				padding: 15px 32px;
				box-sizing: border-box;
			}

			.list {
				width: 100%;
				background: #FFFFFF;
				border-radius: 20rpx;

				.item {
					padding: 0 28rpx 0 32rpx;
					box-sizing: border-box;

					.icon {
						width: 38rpx;
						height: 38rpx;
					}

					.go {
						width: 24rpx;
						height: 24rpx;
					}
				}
			}
		}
	}
</style>